package com.hao.epidemic_prevention.security.passwordencoder;

import lombok.SneakyThrows;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.security.MessageDigest;

public class MyPasswordEncoder implements PasswordEncoder {

    @SneakyThrows
    @Override
    public String encode(CharSequence charSequence) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            byte [] tmp = messageDigest.digest(charSequence.toString().getBytes());

            StringBuilder builder = new StringBuilder("");
            for (byte b : tmp) {
                String str = Integer.toHexString(b & 0xFF);
                if(str.length() == 1) {
                    builder.append("0");
                }
                builder.append(str);
            }
            //System.out.println("加密完成: "+ builder.toString());
            return builder.toString();
        }
        catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    @Override
    public boolean matches(CharSequence charSequence, String s) {
        //System.out.println("匹配中---");
        return s.equals(encode(charSequence));
    }
}
